package com.spzx.channel.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.spzx.channel.domain.ItemVo;
import com.spzx.channel.service.IItemService;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.domain.*;
import io.swagger.v3.oas.annotations.media.Schema;
import org.apache.poi.ss.formula.ptg.Ptg;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;

@Service
public class IItemServiceImpl implements IItemService {

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RedisTemplate redisTemplate;

    //实现远程调用
    @Override
    public ItemVo getItem(Long skuId) {
        String key  = "sku:product:data";
        Boolean bit = redisTemplate.opsForValue().getBit(key, skuId);
        if(!bit){
            throw new ServiceException("查询商品的sku不存在");
        }

        ItemVo itemVo = new ItemVo();
        //远程调用1:skuId获取sku的信息
        R<ProductSku> productSkuR = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
        ProductSku productSku = productSkuR.getData();
        itemVo.setProductSku(productSku);

        //远程调用2: 根据商品id获取商品信息
        Long productId = productSku.getProductId();
        R<Product> productMessageR = remoteProductService.getProductMessage(productId, SecurityConstants.INNER);
        Product product = productMessageR.getData();
        itemVo.setProduct(product);

        //封装轮播图
        String sliderUrls = product.getSliderUrls();
        String[] split1 = sliderUrls.split(",");
        List<String> strings = Arrays.asList(split1);
        itemVo.setSliderUrlList(strings);
        //商品规格信息
        JSONArray jsonArray = JSON.parseArray(product.getSpecValue());
        itemVo.setSpecValueList(jsonArray);

        //远程调用3：获取商品详细信息
        R<ProductDetails> productDetailsR = remoteProductService.getProductDetails(productId, SecurityConstants.INNER);
        ProductDetails productDetails = productDetailsR.getData();
        //获取图片详情数据
        String imageUrls = productDetails.getImageUrls();
        //01.jpg,02.jpg,03.jpg
        //思路：根据逗号分割，得到每个图片，再把每个图片放到list集合
        String[] split = imageUrls.split(",");
//        List<String> arrayList = new ArrayList<>();
//        for (int i = 0; i < split.length; i++) {
//            arrayList.add(split[i]);
//        }
        List<String> arrayList = Arrays.asList(split);
        itemVo.setDetailsImageUrlList(arrayList);


        //远程调用4：获取商品最新价格
        R<SkuPrice> skuPriceR = remoteProductService.getSkuPrice(skuId, SecurityConstants.INNER);
        SkuPrice skuPrice = skuPriceR.getData();
        itemVo.setSkuPrice(skuPrice);

        //远程调用5: 获取商品库存信息
        R<SkuStockVo> skuStockList = remoteProductService.getSkuStock(skuId, SecurityConstants.INNER);
        SkuStockVo skuStockVo = skuStockList.getData();
        itemVo.setSkuStockVo(skuStockVo);

        //远程调用6:获取sku对应商品所有规格
        R<Map<String, Long>> skuSpecValueR = remoteProductService.getSkuSpecValue(productSku.getProductId(),
                SecurityConstants.INNER);
        Map<String, Long> skuSpecValueRData = skuSpecValueR.getData();
        itemVo.setSkuSpecValueMap(skuSpecValueRData);
        return itemVo;


    }
    //TODO 异步编排实现商品详情远程调用情况(并行方式)
    public ItemVo getItem1(Long skuId) {
        String key = "sku:product:data:"+skuId;
        Boolean bit = redisTemplate.opsForValue().getBit(key, skuId);
        if(!bit){
            throw new ServiceException("商品信息sku不存在！");
        }
        ItemVo itemVo = new ItemVo();

        //远程调用接口1:通过skuid查询sku信息
       CompletableFuture<ProductSku> productSkuCompletableFuture =  CompletableFuture.supplyAsync(()->{
            R<ProductSku> productSkuR = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
            ProductSku productSku = productSkuR.getData();
            itemVo.setProductSku(productSku);
            return productSku;
        });
       //远程调用2: 根据商品id获取商品信息
        CompletableFuture<Void> productMessageCompletableFuture = productSkuCompletableFuture.thenAcceptAsync((productSku) -> {
            Long productId = productSku.getProductId();
            R<Product> productMessageR = remoteProductService.getProductMessage(productId, SecurityConstants.INNER);
            Product product = productMessageR.getData();

            itemVo.setProduct(product);
        });
        //远程调用3：根据商品id获取商品详细信息
        CompletableFuture<Void> ProductDetailsCompletableFuture = productSkuCompletableFuture.thenAcceptAsync((productSku) -> {
            Long productId = productSku.getProductId();
            R<ProductDetails> productDetailsR = remoteProductService.getProductDetails(productId, SecurityConstants.INNER);
            ProductDetails productDetails = productDetailsR.getData();
            String imageUrls = productDetails.getImageUrls();
            String[] splitList = imageUrls.split(",");
//            List<String> stringsList = Arrays.stream(splitList).toList();
            List<String> stringList = Arrays.asList(splitList);
            itemVo.setDetailsImageUrlList(stringList);
        });

        //远程调用4：获取商品最新价格
        CompletableFuture<Void> SkuPriceCompletableFuture = CompletableFuture.runAsync(() -> {
            R<SkuPrice> skuPriceR = remoteProductService.getSkuPrice(skuId, SecurityConstants.INNER);
            SkuPrice skuPrice = skuPriceR.getData();
            itemVo.setSkuPrice(skuPrice);
        });

        //远程调用5: 获取商品库存信息
        CompletableFuture<Void> skuStockVoComCompletableFuture = CompletableFuture.runAsync(() -> {
            R<SkuStockVo> skuStockResult = remoteProductService.getSkuStock(skuId, SecurityConstants.INNER);
//            if (R.FAIL == skuStockResult.getCode()) {
//                throw new ServiceException(skuStockResult.getMsg());
//            }
            SkuStockVo skuStockVo = skuStockResult.getData();
            itemVo.setSkuStockVo(skuStockVo);
        });


        //远程调用6:获取sku对应商品所有规格
        CompletableFuture<Void> skuSpecValueCompletableFuture = productSkuCompletableFuture.thenAcceptAsync((productSku) -> {
            Long productId = productSku.getProductId();
            R<Map<String, Long>> skuSpecValueR = remoteProductService.getSkuSpecValue(productId, SecurityConstants.INNER);
            Map<String, Long> skuSpecValueRData = skuSpecValueR.getData();
            itemVo.setSkuSpecValueMap(skuSpecValueRData);
        });
        //等待所有线程操作完成，考虑顺序
        CompletableFuture.allOf(
                productSkuCompletableFuture,
                productMessageCompletableFuture,
                ProductDetailsCompletableFuture,
                SkuPriceCompletableFuture,
                skuStockVoComCompletableFuture,
                skuSpecValueCompletableFuture
        ).join();
        //返回vo对象
        return itemVo;
    }

}
